﻿using ConfExpert.Forms.Aksesuar;
using ConfExpert.Forms.Base;

using DevExpress.Utils;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraReports.UI;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.Aksesuar
{
    public partial class PO : XForm
    {
        public PO()
        {
            InitializeComponent();

            TAM.AksPOTableAdapter = new Datasets.MyDataTableAdapters.AksPOTableAdapter();
            TAM.AksPOLinesTableAdapter = new Datasets.MyDataTableAdapters.AksPOLinesTableAdapter();
        }

        BindingSource bs, bsLines;
        private void AksPO_Load(object sender, EventArgs e)
        {
            GetDetails("AksPO;AksPOLines", "GetAksPOFiltered", 0, 0, string.Empty, 0, 0, string.Empty, 0, 0, 0, string.Empty, WhoAmI);

            string today = DateTime.Today.ToString("d");
            ds.AksPOLines.Columns.Add("O", typeof(int), "Iif(SiparisTarihi is not null, 1, 0)");
            ds.AksPOLines.Columns.Add("N", typeof(int), "Iif(SiparisTarihi is null, 1, 0)");
            ds.AksPOLines.Columns.Add("TerminiGecmis", typeof(int), "Iif(Termin<'" + today + "' and stTalepId in (2,3,6), 1, 0)");
            ds.AksPO.Columns.Add("O", typeof(int), "SUM(Child(FK_AksPOLines_AksPO_AksPOId).O)");
            ds.AksPO.Columns.Add("N", typeof(int), "SUM(Child(FK_AksPOLines_AksPO_AksPOId).N)");
            ds.AksPO.Columns.Add("TerminiGecmis", typeof(int), "SUM(Child(FK_AksPOLines_AksPO_AksPOId).TerminiGecmis)");

            bs = new BindingSource(ds, "AksPO");
            bsLines = new BindingSource(bs, "FK_AksPOLines_AksPO_AksPOId");
            AddBsToList(bs, bsLines);

            InitGridView(gvPO, bs);
            InitGridView(gvPOLines, bsLines);


            gvPOLines.MakeColumnInvisible("O", "N", "AksPOId", "AksPOLinesId", "AksPOSipId", "UserId", "TerminiGecmis", "QtyGelen","AnlasilanFiyat","NumuneVarMi");
            gvPO.SetCaptions("SipNo:TalepNo", "stTalepId:Durum");
            gvPOLines.SetCaptions("QtyNeeded:Talep Adedi", "QtyOrdered:Sipariş Adedi", "QtyGelen:Gelen Adet", "VendorId:Tedarikci", "Notes:Notlar", "stTalepId:Durum");
            gvPO.MakeColumnInvisible("AksPOId", "TerminiGecmis", "Numune", "UserId", "AyrimId","SiparisYeri","IsManuel");

            gvPO.SetFilterTypeToCheckedList("SipNo","OrderRef");


            gvPO.YanYanaGetir("OrderRef:O");

            gvPOLines.YanYanaGetir("stTalepId:AksesuarId", "SiparisTarihi:Termin", "ToplamGelen:SiparisTarihi", "DevamiVarMi:AlternatifNot");

            gvPOLines.MakeReadOnly("QtyNeeded", "Termin");

            gvPOLines.FormatAsNumber(0, "QtyOrdered", "QtyNeeded", "ToplamGelen");
            gvPOLines.FormatAsNumber(4, "AnlasilanFiyat", "FaturaFiyati");
            gvPOLines.FormatAsDate("SiparisTarihi", "Termin");
            gvPOLines.AddSummary("QtyOrdered", "QtyNeeded", "QtyGelen");
            gvPO.AddSummary("O", "N");

            GridManager gm = GridManager.GetManager(gvPO);
            gm.GridMenu.AddMenu("Talebi satınalmaya ilet", SubmitOrders);
            gm.GridMenu.AddMenu("İptal et", CancelOrders);
            gm.GridMenu.AddMenu("Sipariş föyü çıkar", PrintPurchaseFoy);
            gm.GridMenu.AddMenu("OrderRef belirle", SetOrderRef);

            btnGetir.Click += new EventHandler(btnGetir_Click);
            btnTemizle.Click += new EventHandler(btnTemizle_Click);

            CreateVerticalGrid();

            gvPOLines.CellValueChanged += gvPOLines_CellValueChanged;
            gvPO.FocusedRowChanged += gvPO_FocusedRowChanged;
            gvPOLines.FocusedRowChanged += gvPOLines_FocusedRowChanged;
            gvPOLines.DoubleClick += gvPOLines_DoubleClick;
            gvPOLines.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(gvPOLines_RowCellStyle);
            gvPO.RowCellStyle += gvPO_RowCellStyle;
            bbiSave.ItemClick += bbiSave_ItemClick;
            gvPO_FocusedRowChanged(null, null);

            Exp(true);
            splitContainerControl1.AutoSize();
            gvPO.BestFitColumns();
            gvPOLines.BestFitColumns();
        }

        void gvPOLines_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gvPO.FocusedRowHandle > -1)
            {
                int stTalepId = gvPO.GetRowCellValue(gvPO.FocusedRowHandle, "stTalepId").ToInt();
                if (stTalepId == 1 || ytk(66))
                {
                    gvPOLines.MakeReadOnly("QtyNeeded", "Termin", "Notes");
                }
                else
                {
                    int PoLinesDurum = gvPOLines.GetRowCellValue(gvPOLines.FocusedRowHandle, "stTalepId").ToInt();
                    if (PoLinesDurum == 1 || PoLinesDurum == 2)//PoLines'ın durumu sipariş verildi değil ise not değiştirmeye izin ver..
                        gvPOLines.MakeReadOnly("Notes");
                    else
                        gvPOLines.MakeReadOnly();
                }
            }
        }

        private void SetOrderRef(object sender, EventArgs e)
        {
            gvPO.EndEditing();
            gvPOLines.EndEditing();

            if (ds.HasChanges())
            {
                bbiSave.PerformClick();
            }

            int BrandId = gvPO.GetFocusedRowCellValue("BrandId").ToInt();
            int SezonId = gvPO.GetFocusedRowCellValue("SezonId").ToInt();
            int AksPOId = gvPO.GetFocusedRowCellValue("AksPOId").ToInt();
            string OrderRef = gvPO.GetFocusedRowCellValue("OrderRef").ToStr();

            using (AksPOAyirmTanimla ah = new AksPOAyirmTanimla(BrandId, SezonId, OrderRef, AksPOId))
            {
                DialogResult dr = ah.ShowDialog();
                if (dr == DialogResult.OK)
                    Yenile();
            }
        }

        void gvPOLines_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "QtyNeeded")
                {
                    decimal QtyNeeded = gvPOLines.GetRowCellValue(e.RowHandle, "QtyNeeded").ToDecimal();
                    gvPOLines.SetRowCellValue(e.RowHandle, "QtyOrdered", QtyNeeded);
                }
            }
        }

        void gvPOLines_DoubleClick(object sender, EventArgs e)
        {
            int handle = gvPOLines.FocusedRowHandle;
            if (handle > -1)
            {
                int AksesuarId = intParse(gvPOLines.GetRowCellValue(handle, "AksesuarId"));
                using (AksesuarHareketGC ah = new AksesuarHareketGC(AksesuarId, null, null))
                    ah.ShowDialog();
            }
        }

        void gvPO_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gvPO.FocusedRowHandle > -1)
            {
                int stTalepId = gvPO.GetRowCellValue(gvPO.FocusedRowHandle, "stTalepId").ToInt();

                if (stTalepId == 1 || ytk(66))
                    gvPO.MakeReadOnly("BrandId", "SezonId", "Numune");
                else        
                    gvPO.MakeReadOnly();

                gvPOLines_FocusedRowChanged(null, null);
            }
        }

        private void CancelOrders(object sender, EventArgs e)
        {
            //ConfExpert.Datasets.MyData.AksPORow ar = ds.AksPO.FindByAksPOId(gvPO.GetFocusedRowCellValue("AkspoId").ToInt());
            DataRow[] dr = ds.AksPO.Select("AksPOId in (" + gvPO.GetSelectedValues("AksPOId") + ") and stTalepId=1");
            if (dr.Length > 0)
            {
                foreach (DataRow drItem in dr)
                {
                    int AksPOId = drItem["AksPOId"].ToInt();
                    ds.AksPO.FindByAksPOId(AksPOId)["stTalepId"] = 4;
                }
                bbiSave.PerformClick();
                Yenile();
            }
        }

        private void SubmitOrders(object sender, EventArgs e)
        {

            DataRow[] dr = ds.AksPO.Select("AksPOId in (" + gvPO.GetSelectedValues("AksPOId") + ") and stTalepId=1");
            if (dr.Length > 0)
            {
                foreach (DataRow drItem in dr)
                {
                    int AksPOId = drItem["AksPOId"].ToInt();
                    ds.AksPO.FindByAksPOId(AksPOId)["stTalepId"] = 2;
                    ds.AksPO.FindByAksPOId(AksPOId)["TalepTarihi"] = DateTime.Now;
                }
                bbiSave.PerformClick();
                Yenile();
            }
        }

        void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvPO.EndEditing();
            gvPOLines.EndEditing();
            Exp(false);
            Save();
            Exp(true);
        }

        private void PrintPurchaseFoy(object sender, EventArgs e)
        {
            string ids = gvPO.GetSelectedValues("AksPOId");
            Rapor.Aksesuar.xrAksesuarSiparisFoy asf = new Rapor.Aksesuar.xrAksesuarSiparisFoy(ids, "GetAksesuarSiparisFoyu", "AksPOId");
            asf.ShowPreview();
        }

        void Exp(bool set)
        {
            //ds.AksPOLines.Columns["QtyOrdered"].Expression = set ? "ISNULL(QtyRevised,QtyNeeded)" : string.Empty;
            string today = DateTime.Today.ToString("d");
            ds.AksPOLines.Columns["TerminiGecmis"].Expression = set ? "Iif(Termin<'" + today + "' and stTalepId in (2,3,6), 1, 0)" : string.Empty;
            ds.AksPOLines.Columns["O"].Expression = set ? "Iif(SiparisTarihi is not null, 1, 0)" : string.Empty;
            ds.AksPOLines.Columns["N"].Expression = set ? "Iif(SiparisTarihi is null, 1, 0)" : string.Empty;

            ds.AksPO.Columns["TerminiGecmis"].Expression = set ? "SUM(Child(FK_AksPOLines_AksPO_AksPOId).TerminiGecmis)" : string.Empty;
            ds.AksPO.Columns["O"].Expression = set ? "SUM(Child(FK_AksPOLines_AksPO_AksPOId).O)" : string.Empty;
            ds.AksPO.Columns["N"].Expression = set ? "SUM(Child(FK_AksPOLines_AksPO_AksPOId).N)" : string.Empty;
        }

        void gvPO_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "stTalepId")
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);

            int TerminiGecmis = gvPO.GetRowCellValue(e.RowHandle, "TerminiGecmis").ToInt();
            int stTalepId = gvPO.GetRowCellValue(e.RowHandle, "stTalepId").ToInt();
            if (e.Column.FieldName == "stTalepId" && TerminiGecmis > 0 && (stTalepId == 3 || stTalepId == 6 || stTalepId == 2))
            {
                e.Appearance.ForeColor = Color.Red;
            }
        }

        void gvPOLines_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "QtyNeeded" ||
                e.Column.FieldName == "QtyOrdered" ||
                e.Column.FieldName == "AksesuarId"
                )
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);

            int TerminiGecmis = gvPOLines.GetRowCellValue(e.RowHandle, "TerminiGecmis").ToInt();
            if (TerminiGecmis > 0)
            {
                e.Appearance.BackColor = Color.LightPink;
            }
        }


        private void CreateVerticalGrid()
        {
            vgc.Rows.AddRange(new BaseRow[] {
                AddItem("TumTalepler", typeof(bool)),
                AddItem("stTalepId", typeof(int), RI(Rp.stTalep)),
                AddItem("SipNo", typeof(string)),
                AddItem("TalepEdenId", typeof(int), RI(Rp.V_User)),
                AddItem("BrandId", typeof(int), RI(Rp.Brand)),
                AddItem("Numune", typeof(string)),
                AddItem("ProductCategoryId", typeof(int), RI(Rp.ProductCategory)),
                AddItem("AksesuarId", typeof(int), RI(Rp.V_Aksesuar)),
                AddItem("Tedarikci", typeof(int), RI(Rp.Vendor)),
                AddItem("Notes", typeof(string))
            });

            vgc.Rows.GetRowByFieldName("Notes", true).Height = 80;

            vgc.OptionsBehavior.UseEnterAsTab = true;
            vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;
            vgc.CustomDrawRowHeaderCell += new DevExpress.XtraVerticalGrid.Events.CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;

            vgc.BestFit();
        }

        public BaseRow AddItem(string name, Type t, params RepositoryItem[] ri)
        {
            return AddItem(vgc, name, t, ri);
        }

        object GetVal(string FieldName)
        {
            return vgc.GetCellValue(vgc.Rows[FieldName], vgc.FocusedRecord);
        }

        void btnGetir_Click(object sender, EventArgs e)
        {
            Yenile();

        }

        private void Yenile()
        {
            int focusedRow = gvPO.FocusedRowHandle;
            ds.Clear();

            GetDetails("AksPO;AksPOLines", "GetAksPOFiltered",
                boolParse(GetVal("TumTalepler")),
                intParse(GetVal("stGenelId")),
                strParse(GetVal("SipNo")),
                intParse(GetVal("TalepEdenId")),
                intParse(GetVal("BrandId")),
                strParse(GetVal("Numune")),
                intParse(GetVal("ProductCategoryId")),
                intParse(GetVal("AksesuarId")),
                intParse(GetVal("Tedarikci")),
                strParse(GetVal("Aciklama")),
                WhoAmI
                );

            gvPO.BestFitColumns();

            if (focusedRow + 1 >= gvPO.RowCount)
            {
                gvPO.FocusedRowHandle = gvPO.RowCount - 2;
            }
            else
            {
                gvPO.FocusedRowHandle = focusedRow;
            }
            Notify("Done.");
        }

        void btnTemizle_Click(object sender, EventArgs e)
        {
            foreach (BaseRow r in vgc.Rows)
                vgc.SetCellValue(r, 0, null);
        }

        private void dockPanel1_Click(object sender, EventArgs e)
        {

        }
    }
}